// 导入依赖组件

// 学生管理组件
function StudentManagement() {
    const [students, setStudents] = React.useState([]);
    const [loading, setLoading] = React.useState(true);
    const [searchTerm, setSearchTerm] = React.useState('');
    const [currentPage, setCurrentPage] = React.useState(1);
    const [itemsPerPage, setItemsPerPage] = React.useState(10);
    const [totalCount, setTotalCount] = React.useState(0);
    const [showModal, setShowModal] = React.useState(false);
    const [editingUser, setEditingUser] = React.useState(null);

    // 获取学生数据
    const fetchStudents = React.useCallback(async (page = 1, search = '') => {
        setLoading(true);
        try {
            const result = await Utils.fetchData(
                Utils.getApiUrl(`/chm/api/users/students?page=${page}&size=${itemsPerPage}&search=${encodeURIComponent(search)}`)
            );
            
            setStudents(result.data.rows || []);
            setTotalCount(result.data.count || 0);
        } catch (error) {
            console.error('获取学生数据失败:', error);
            Utils.showAlert('获取学生数据失败，请检查网络连接或重新登录', 'error');
            setStudents([]);
            setTotalCount(0);
        } finally {
            setLoading(false);
        }
    }, [itemsPerPage]);

    // 组件挂载时获取数据
    React.useEffect(() => {
        fetchStudents(currentPage, searchTerm);
    }, [fetchStudents, currentPage, searchTerm]);

    // 分页计算
    const totalPages = Math.ceil(totalCount / itemsPerPage);

    // 处理搜索
    const handleSearch = (e) => {
        setSearchTerm(e.target.value);
        setCurrentPage(1);
    };

    // 处理分页
    const handlePageChange = (page) => {
        setCurrentPage(page);
    };
    
    // 处理每页条数变化
    const handleItemsPerPageChange = (newItemsPerPage) => {
        setItemsPerPage(newItemsPerPage);
        setCurrentPage(1); // 重置到第1页
    };

    // 新增学生
    const handleAddStudent = () => {
        setEditingUser(null);
        setShowModal(true);
    };

    // 编辑学生
    const handleEditStudent = (student) => {
        setEditingUser(student);
        setShowModal(true);
    };

    // 处理表单提交
    const handleFormSubmit = async (formData) => {
        try {
            const isEditing = !!editingUser;
            const url = isEditing 
                ? Utils.getApiUrl(`/chm/api/users/${editingUser.id}`)
                : Utils.getApiUrl('/chm/api/users');
            
            const requestData = {
                realName: formData.realName,
                email: formData.email,
                phone: formData.phone,
                username: formData.phone, // 用户名设置为手机号
                role: 'STUDENT'
            };
            
            await (isEditing ? Utils.updateItem(url, requestData) : Utils.createItem(url, requestData));
            
            Utils.showAlert(isEditing ? '学生信息更新成功' : '学生添加成功', 'success');
            setShowModal(false);
            fetchStudents(currentPage, searchTerm); // 刷新列表
        } catch (error) {
            console.error(isEditing ? '更新学生信息失败:' : '添加学生失败:', error);
            Utils.showAlert(isEditing ? '更新学生信息失败，请检查网络连接' : '添加学生失败，请检查网络连接', 'error');
        }
    };

    // 导入学生
    const handleImportStudents = () => {
        Utils.showAlert('导入学生功能开发中...', 'info');
    };

    // 删除学生
    const handleDeleteStudent = async (student) => {
        if (confirm(`确定要删除学生 ${student.realName} 吗？`)) {
            try {
                const url = Utils.getApiUrl(`/chm/api/users/${student.id}`);
                await Utils.deleteItem(url);
                
                Utils.showAlert('学生删除成功', 'success');
                fetchStudents(currentPage, searchTerm); // 刷新列表
            } catch (error) {
                console.error('删除学生失败:', error);
                Utils.showAlert('删除学生失败，请检查网络连接', 'error');
            }
        }
    };

    // 表格列定义
    const columns = [
        { title: 'ID', field: 'id' },
        { title: '学号', value: (student) => student.studentId || 'N/A' },
        { title: '用户名', field: 'username' },
        { title: '姓名', field: 'realName' },
        { title: '班级', value: (student) => student.className || 'N/A' },
        { title: '邮箱', field: 'email' },
        { title: '手机号', field: 'phone' },
        { 
            title: '角色', 
            value: (student) => 
                React.createElement('span', { 
                    className: `px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
                        student.role === 'ADMIN' ? 'bg-purple-100 text-purple-800' : 
                        student.role === 'TEACHER' ? 'bg-blue-100 text-blue-800' : 'bg-green-100 text-green-800'
                    }`
                }, student.role === 'ADMIN' ? '管理员' : student.role === 'TEACHER' ? '教师' : '学生')
        },
        { 
            title: '创建时间', 
            value: (student) => student.createTime ? new Date(student.createTime).toLocaleDateString('zh-CN') : 'N/A'
        }
    ];

    // 操作按钮定义
    const actions = [
        { label: '导入学生', onClick: handleImportStudents, primary: false },
        { label: '新增学生', onClick: handleAddStudent, primary: true }
    ];

    // 渲染行操作按钮
    const renderRowActions = (student) => 
        React.createElement(React.Fragment, null,
            React.createElement('button', { 
                onClick: () => handleEditStudent(student),
                className: 'text-blue-600 hover:text-blue-900 mr-3'
            }, '编辑'),
            React.createElement('button', { 
                onClick: () => handleDeleteStudent(student),
                className: 'text-red-600 hover:text-red-900'
            }, '删除')
        );

    return React.createElement(React.Fragment, null,
        // 用户表单模态框
        React.createElement(UserFormModal, {
            isOpen: showModal,
            onClose: () => setShowModal(false),
            onSubmit: handleFormSubmit,
            user: editingUser,
            role: 'student'
        }),
        
        React.createElement('div', { className: 'p-6' },
            React.createElement(DataTable, {
                title: '学生管理',
                description: '管理系统中所有学生账户信息',
                columns: columns,
                data: students,
                loading: loading,
                searchValue: searchTerm,
                onSearch: handleSearch,
                searchPlaceholder: '搜索学号、用户名、姓名、班级、邮箱或手机号...',
                currentPage: currentPage,
                totalPages: totalPages,
                totalCount: totalCount,
                itemsPerPage: itemsPerPage,
                onPageChange: handlePageChange,
                onItemsPerPageChange: handleItemsPerPageChange,
                actions: actions,
                renderRowActions: renderRowActions
            })
        )
    );
}

// 将组件暴露到全局作用域，使其可被其他脚本访问
window.StudentManagement = StudentManagement;